from fastapi import APIRouter, Depends, Form, Request
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from sqlalchemy import func
from datetime import timedelta, date, datetime, timedelta
from ..models import get_db, Contact, Link, Tag, Title, WebsiteConfig, User, SearchEngine, StaticPage, VisitStat
from ..auth import authenticate_user, create_access_token, get_current_user
from ..config import ACCESS_TOKEN_EXPIRE_MINUTES
import os

router = APIRouter()

# 获取模板目录
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "templates"))

# 登录页面
@router.get("/login", response_class=HTMLResponse)
async def admin_login(request: Request, db: Session = Depends(get_db)):
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(
            site_name="",
            site_description="",
            personal_intro="",
            icp_record="",
            copyright_info="",
            background_effect="stars"
        )
    return templates.TemplateResponse("admin/login.html", {"request": request, "config": config})

# 登录处理
@router.post("/login")
async def admin_login_post(
    request: Request,
    username: str = Form(...),
    password: str = Form(...),
    db: Session = Depends(get_db)
):
    user = authenticate_user(db, username, password)
    if not user:
        # 获取重定向参数（如果有）
        redirect_url = request.query_params.get("redirect", "")
        return templates.TemplateResponse(
            "admin/login.html", 
            {"request": request, "error": "用户名或密码错误", "redirect": redirect_url}
        )
    
    # 创建访问令牌
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    
    # 获取重定向参数（如果有），否则默认重定向到仪表盘
    redirect_url = request.query_params.get("redirect", "/admin/dashboard")
    # 确保重定向URL是安全的（只允许admin目录下的页面）
    if not redirect_url.startswith("/admin/"):
        redirect_url = "/admin/dashboard"
    
    # 设置cookie并重定向，同时设置cookie过期时间与令牌一致
    response = RedirectResponse(url=redirect_url, status_code=302)
    response.set_cookie(
        key="access_token", 
        value=access_token, 
        httponly=True,
        max_age=ACCESS_TOKEN_EXPIRE_MINUTES * 60,  # 转换为秒
        expires=ACCESS_TOKEN_EXPIRE_MINUTES * 60   # 过期时间（秒）
    )
    return response

# 登出处理
@router.get("/logout")
async def admin_logout():
    response = RedirectResponse(url="/admin/login")
    response.delete_cookie("access_token")
    return response

# 修改密码页面
@router.get("/change-password", response_class=HTMLResponse)
async def change_password_page(
    request: Request, 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(
            site_name="",
            site_description="",
            personal_intro="",
            icp_record="",
            copyright_info="",
            background_effect="stars"
        )
    
    return templates.TemplateResponse(
        "admin/change-password.html", 
        {
            "request": request, 
            "current_user": current_user,
            "config": config
        }
    )

# 修改密码处理
@router.post("/change-password")
async def change_password_post(
    request: Request,
    old_password: str = Form(...),
    new_password: str = Form(...),
    confirm_password: str = Form(...),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(
            site_name="",
            site_description="",
            personal_intro="",
            icp_record="",
            copyright_info="",
            background_effect="stars"
        )
    
    # 检查是否为AJAX请求
    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
    
    # 验证新密码和确认密码是否一致
    if new_password != confirm_password:
        if is_ajax:
            return JSONResponse(status_code=400, content={"success": False, "message": "新密码和确认密码不一致"})
        return templates.TemplateResponse(
            "admin/change-password.html", 
            {
                "request": request, 
                "current_user": current_user,
                "config": config,
                "error": "新密码和确认密码不一致"
            }
        )
    
    # 验证新密码长度
    if len(new_password) < 6:
        if is_ajax:
            return JSONResponse(status_code=400, content={"success": False, "message": "新密码长度不能少于6个字符"})
        return templates.TemplateResponse(
            "admin/change-password.html", 
            {
                "request": request, 
                "current_user": current_user,
                "config": config,
                "error": "新密码长度不能少于6个字符"
            }
        )
    
    # 修改密码
    from ..auth import update_user_password
    if update_user_password(db, current_user, old_password, new_password):
        if is_ajax:
            return JSONResponse(status_code=200, content={"success": True, "message": "密码修改成功"})
        return templates.TemplateResponse(
            "admin/change-password.html", 
            {
                "request": request, 
                "current_user": current_user,
                "config": config,
                "success": "密码修改成功"
            }
        )
    else:
        if is_ajax:
            return JSONResponse(status_code=400, content={"success": False, "message": "原密码错误"})
        return templates.TemplateResponse(
            "admin/change-password.html", 
            {
                "request": request, 
                "current_user": current_user,
                "config": config,
                "error": "原密码错误"
            }
        )

# 仪表盘
@router.get("/dashboard", response_class=HTMLResponse)
async def admin_dashboard(
    request: Request, 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    # 获取统计数据
    contacts_count = db.query(Contact).count()
    links_count = db.query(Link).count()
    tags_count = db.query(Tag).count()
    titles_count = db.query(Title).count()
    search_engines_count = db.query(SearchEngine).count()
    static_pages_count = db.query(StaticPage).count()
    
    # 获取访问量统计
    today = date.today()
    # 今日访问量
    today_visits = db.query(VisitStat).filter(VisitStat.visit_date == today).first()
    today_visit_count = today_visits.visit_count if today_visits else 0
    
    # 昨日访问量
    yesterday = today - timedelta(days=1)
    yesterday_visits = db.query(VisitStat).filter(VisitStat.visit_date == yesterday).first()
    yesterday_visit_count = yesterday_visits.visit_count if yesterday_visits else 0
    
    # 总访问量
    total_visits = db.query(func.sum(VisitStat.visit_count)).scalar() or 0
    
    # 近7天访问量趋势（已移除图表显示）
    last_7_days = []
    
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(
            site_name="",
            site_description="",
            personal_intro="",
            icp_record="",
            copyright_info="",
            background_effect="stars"
        )
    
    return templates.TemplateResponse(
        "admin/dashboard.html", 
        {
            "request": request, 
            "current_user": current_user,
            "contacts_count": contacts_count,
            "links_count": links_count,
            "tags_count": tags_count,
            "titles_count": titles_count,
            "search_engines_count": search_engines_count,
            "static_pages_count": static_pages_count,
            "today_visit_count": today_visit_count,
            "yesterday_visit_count": yesterday_visit_count,
            "total_visits": total_visits,
            "config": config
        }
    )